package com.nifostasky.comic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nifostasky.comic.entitys.SysOrg;
import com.nifostasky.comic.exceptions.BusinessException;
import com.nifostasky.comic.mapper.SysOrgMapper;
import com.nifostasky.comic.service.SysOrgService;
import com.nifostasky.comic.dtos.SysOrgDTO;
import com.nifostasky.comic.enums.SysOrgStatusEnum;
import com.nifostasky.comic.utils.PageUtils;
import com.nifostasky.comic.vos.ResultCode;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@Service
public class SysOrgServiceImpl extends ServiceImpl<SysOrgMapper, SysOrg> implements SysOrgService {

    @Override
    public SysOrgDTO findDetailByCode(String orgCode) {
        QueryWrapper<SysOrg> wrapper = new QueryWrapper<>();
        wrapper = wrapper.eq("org_code",orgCode);
        SysOrg one = super.getOne(wrapper);
        if (null == one){
            return null;
        }
        SysOrgDTO dto = new SysOrgDTO();
        BeanUtils.copyProperties(one,dto);
        return dto;
    }

    @Override
    public IPage<SysOrg> findListPage(PageUtils pageUtils, SysOrg sysOrg) {
        LambdaQueryWrapper<SysOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(sysOrg.getOrgName()),SysOrg::getOrgName,sysOrg.getOrgName());
        queryWrapper.like(StringUtils.isNotBlank(sysOrg.getAliasName()),SysOrg::getAliasName,sysOrg.getAliasName());
        queryWrapper.eq(Objects.nonNull(sysOrg.getParentId()),SysOrg::getParentId,sysOrg.getParentId());
        queryWrapper.eq(Objects.nonNull(sysOrg.getOrgType()),SysOrg::getOrgType,sysOrg.getOrgType());
        queryWrapper.eq(Objects.nonNull(sysOrg.getOrgLevel()),SysOrg::getOrgLevel,sysOrg.getOrgLevel());
        queryWrapper.eq(Objects.nonNull(sysOrg.getOrgStatus()),SysOrg::getOrgStatus,sysOrg.getOrgStatus());
        queryWrapper.orderByAsc(SysOrg::getSort).orderByDesc(SysOrg::getCreateDate);
        IPage<SysOrg> page = this.baseMapper.selectPage(new Page<>(pageUtils.getPageIndex(),pageUtils.getPageSize()),queryWrapper);
        return page;
    }

    @Override
    public List<SysOrg> findList(SysOrg sysOrg) {
        LambdaQueryWrapper<SysOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(sysOrg.getOrgName()),SysOrg::getOrgName,sysOrg.getOrgName());
        queryWrapper.like(StringUtils.isNotBlank(sysOrg.getAliasName()),SysOrg::getAliasName,sysOrg.getAliasName());
        queryWrapper.eq(Objects.nonNull(sysOrg.getParentId()),SysOrg::getParentId,sysOrg.getParentId());
        queryWrapper.eq(Objects.nonNull(sysOrg.getOrgType()),SysOrg::getOrgType,sysOrg.getOrgType());
        queryWrapper.eq(Objects.nonNull(sysOrg.getOrgLevel()),SysOrg::getOrgLevel,sysOrg.getOrgLevel());
        queryWrapper.eq(Objects.nonNull(sysOrg.getOrgStatus()),SysOrg::getOrgStatus,sysOrg.getOrgStatus());
        queryWrapper.orderByAsc(SysOrg::getSort).orderByDesc(SysOrg::getCreateDate);
        return this.list(queryWrapper);
    }

    @Override
    public Boolean saveOrUpdateOrg(SysOrg sysOrg) {
        //验证同一级orgNum不能重复
        SysOrg onlyOrg = this.getOrgByParentIdAndOrgNum(sysOrg.getParentId(),sysOrg.getOrgNum());
        if (Objects.nonNull(onlyOrg)) {
            if (Objects.isNull(sysOrg.getId())) {
                throw new BusinessException("机构编号已存在");
            } else if (Objects.nonNull(sysOrg.getId()) && !Objects.equals(sysOrg.getId(), onlyOrg.getId())) {
                throw new BusinessException("机构编号已存在");
            }
        }
        if(Objects.isNull(sysOrg.getId())){
            //获取父级org
            SysOrg org = this.getById(sysOrg.getParentId());
            sysOrg.setOrgCode(genOrgCode(org.getOrgCode(),sysOrg.getOrgNum()));
        }else{
            //不修改的数据
            sysOrg.setOrgNum(null);
            sysOrg.setOrgCode(null);
        }
        return this.saveOrUpdate(sysOrg);
    }

    @Override
    public SysOrg getOrgByParentIdAndOrgNum(Long parentId, Integer orgNum) {
        LambdaQueryWrapper<SysOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysOrg::getParentId,parentId);
        queryWrapper.eq(SysOrg::getOrgNum,orgNum);
        return this.getOne(queryWrapper);
    }

    @Override
    public Boolean deleteById(Long id) {
        if(Objects.isNull(id)){
            throw new BusinessException(ResultCode.REQUIRED_PARAMS);
        }
        //查询是否有子集
        List<SysOrg> listOrg = this.findChildListByOrgId(id);
        if(CollectionUtils.isNotEmpty(listOrg)){
            throw new BusinessException(ResultCode.SYS_CHILD_EXIST);
        }
        return this.removeById(id);
    }

    @Override
    public Boolean updateOrgStatusById(Long id, Integer orgStatus) {
        if(Objects.isNull(id) || Objects.isNull(orgStatus)){
            throw new BusinessException(ResultCode.REQUIRED_PARAMS);
        }
        if(SysOrgStatusEnum.STATUS_TWO.getCode().equals(orgStatus)){
            //查询是否有子集
            List<SysOrg> listOrg = this.findChildListByOrgId(id);
            if(CollectionUtils.isNotEmpty(listOrg)){
                throw new BusinessException(ResultCode.SYS_CHILD_EXIST);
            }
        }
        UpdateWrapper<SysOrg> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(SysOrg::getOrgStatus,orgStatus);
        updateWrapper.lambda().eq(SysOrg::getId,id);
        return this.update(updateWrapper);
    }

    @Override
    public List<SysOrg> findChildListByOrgId(Long id) {
        LambdaQueryWrapper<SysOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysOrg::getParentId,id);
        return this.list(queryWrapper);
    }

    private String genOrgCode(String parentCode,Integer orgNum){
        StringBuffer sb = new StringBuffer();
        sb.append(parentCode).append(orgNum).append(".");
        return sb.toString();
    }
    /**
     * 平台用户(superManger: -1)
     * @param userType
     * @return
     */
    private Set setTYpeForSuperManage(String userType){
        Set orgTypes = new HashSet();
        if("-1".equals(userType)){
            orgTypes.add(1);
            orgTypes.add(2);
            orgTypes.add(3);
            orgTypes.add(4);
            return orgTypes;
        }else{
            orgTypes.add(userType);
            return orgTypes;
        }
    }






}
